﻿using Cherry.Agile.UI.Framework.Security;
using Cherry.Agile.Security;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Mvc;
using System.Web.Mvc.Filters;

namespace Cherry.Agile.Framework.Security
{
    public class AgileAuthAttribute:ActionFilterAttribute, IAuthorizationFilter
    {
        public string ModuleName
        {
            set;
            get;
        }

        public string ControlName
        {
            set;
            get;
        }

        public string Code
        {
            set;
            get;
        }

        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            //if (filterContext.HttpContext.User != null && filterContext.HttpContext.User.Identity.IsAuthenticated)
            //{
            //    string areaName = (string)filterContext.RouteData.DataTokens["area"];
            //    string controllerName = (string)filterContext.RouteData.Values["controller"];
            //    string actionName = (string)filterContext.RouteData.Values["action"];
            //    if (filterContext.HttpContext.User.HasPermission(string.Format("{0}_{1}", controllerName, actionName)))
            //    {
            //        base.OnActionExecuting(filterContext);
            //    }
            //    else
            //    {
            //        filterContext.Result = new ViewResult { ViewName = "NoPermission" };
            //    }

            //}
            //else
            //{
            //    filterContext.Result = new ViewResult { ViewName = "Index" };
            //}
            //if(filterContext.RouteData.DataTokens["area"])
            ModuleName = (string)filterContext.RouteData.DataTokens["area"];
            ControlName = (string)filterContext.RouteData.Values["controller"];
            Code = (string)filterContext.RouteData.Values["action"];
            base.OnActionExecuting(filterContext);
        }

        public void OnAuthorization(AuthorizationContext filterContext)
        {
            var user = filterContext.HttpContext.User;

        }

        public void OnAuthenticationChallenge(AuthenticationChallengeContext filterContext)
        {
            var user = filterContext.HttpContext.User;
            if (user == null || !user.Identity.IsAuthenticated)
            {
                filterContext.Result = new HttpUnauthorizedResult();
            }
            else 
            {
                if(!filterContext.HttpContext.User.HasPermission(string.Format(@"{0}/{1}_{2}",ModuleName,ControlName, Code)))
                {
                    filterContext.Result = new HttpUnauthorizedResult();
                }
                else
                {
                    //fileterContext.Result = new Httpl
                }
            }
        }
    }
}
